﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DataBaseFactoryLib;

namespace SQLToolsCore
{
    public partial class DataAdder : Form
    {
        private const int LABEL_WIDTH = 180, LABEL_HEIGHT = 21,
            TEXT_WIDTH = 120, TEXT_HEIGHT = 34, SPACE = 10;

        private int lastPointLength = 0;
        private readonly string tableName;
        private DataTable structueDt, tablesInfoDt;
        private TextBoxEx primaryKeyText;
        private readonly BaseDataBaseOpr db = DBHelper.GetInstanse();

        public DataAdder(DataTable structue, string tableNameStr)
        {
            tableName = tableNameStr;
            tablesInfoDt = GetTableIDInfo();
            InitializeComponent();
            structueDt = structue;
            if (structue.Rows.Count > 0)
            {
                var size = GetAutoSize(structue.Rows.Count);
                WinFormResize(structue, size);
            }
            if (!string.IsNullOrWhiteSpace(tableNameStr))
            {
                this.Text = this.Text + "：" + tableNameStr;
            }

            this.MaximizeBox = false;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }

        /// <summary>
        /// 根据数据字段数获取窗口长宽
        /// </summary>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        private static int[] GetAutoSize(int rowCount)
        {
            var rtnVal = new int[] { 0, 0 };

            if (rowCount < 2)
            {
                rtnVal[0] = LABEL_WIDTH + TEXT_WIDTH + SPACE + 20 * 2 + 15 - 2;
            }
            else
            {
                rtnVal[0] = (LABEL_WIDTH + TEXT_WIDTH + SPACE + 20) * 2 + 35 - 2;
            }

            rtnVal[1] = (20 + LABEL_HEIGHT) * ((rowCount + 1) / 2) + 100 - 1;

            return rtnVal;
        }

        /// <summary>
        /// 根据条件重置窗体
        /// </summary>
        /// <param name="structue"></param>
        /// <param name="sizes"></param>
        private void WinFormResize(DataTable structue, int[] sizes)
        {
            this.Width = sizes[0];
            this.Height = sizes[1];

            for (int i = 0; i < structue.Rows.Count; i++)
            {
                Label label = new()
                {
                    AutoSize = false,
                    Width = LABEL_WIDTH,
                    Height = LABEL_HEIGHT,
                    TextAlign = ContentAlignment.MiddleRight
                };

                TextBoxEx textBox = new()
                {
                    Width = TEXT_WIDTH,
                    Height = TEXT_HEIGHT
                };

                if (i % 2 == 0)
                {
                    label.Location = new Point(20, 20 + (20 + LABEL_HEIGHT) * (i / 2));
                    textBox.Location = new Point(20 + LABEL_WIDTH + SPACE, 20 + (20 + LABEL_HEIGHT) * (i / 2));
                }
                else
                {
                    label.Location = new Point(LABEL_WIDTH + TEXT_WIDTH + SPACE + 40,
                        20 + (20 + LABEL_HEIGHT) * (i / 2));
                    textBox.Location = new Point(LABEL_WIDTH + TEXT_WIDTH + SPACE + 40 + LABEL_WIDTH + SPACE,
                        20 + (20 + LABEL_HEIGHT) * (i / 2));
                }
                label.Text = structue.Rows[i]["字段名"].ToString() +
                    (string.IsNullOrWhiteSpace(structue.Rows[i]["别名"].ToString()) ?
                    "" : "(" + structue.Rows[i]["别名"].ToString() + ")");
                label.Name = structue.Rows[i]["字段名"].ToString();
                textBox.Name = structue.Rows[i]["字段名"].ToString() + "_value";
                textBox.PlaceHolderStr = structue.Rows[i]["数据类型"].ToString();

                if (label.Name == tablesInfoDt.Rows[0]["id0_field"].ToString())
                {
                    textBox.Enabled = false;
                    textBox.Text = (int.Parse(tablesInfoDt.Rows[0]["cur_id0"].ToString()) + 1).ToString();
                    primaryKeyText = textBox;
                }

                this.Controls.Add(label);
                this.Controls.Add(textBox);

                if (i == structue.Rows.Count - 1)
                {
                    lastPointLength = textBox.Location.Y + textBox.Height;
                }
            }

            //按钮重新定位
            button1.Location = new Point((this.Width - button1.Width) / 2,
                lastPointLength + 20);
        }

        /// <summary>
        /// 获取表信息Dt
        /// </summary>
        /// <param name="getDataTablesBySQL"></param>
        /// <returns></returns>
        private DataTable GetTableIDInfo()
        {
            string sqlStr = @"SELECT * FROM dbo.ZY_T_D_TablesInfo
            WHERE table_name = '" + tableName + "'";

            var tempDt = db.QueryDataTable(sqlStr);

            return tempDt;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string insertValStr = string.Empty;
            foreach (DataRow item in structueDt.Rows)
            {
                var temp = this.Controls.Find(item["字段名"].ToString() + "_value", false);
                var itemType = GetColumnType(item["数据类型"].ToString());
                if (itemType == 0)
                {
                    if (string.IsNullOrWhiteSpace(temp[0].Text) && item["空否"].ToString() == "N")
                    {
                        MessageBox.Show(item["字段名"].ToString() + "不能为空!");
                        return;
                    }
                    insertValStr += temp[0].Text + ",";
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(temp[0].Text) && item["空否"].ToString() == "N")
                    {
                        MessageBox.Show(item["字段名"].ToString() + "不能为空!");
                        return;
                    }
                    if (itemType == 2)
                    {
                        var tempDate = new DateTime();
                        if (!DateTime.TryParse(temp[0].Text, out tempDate))
                        {

                            MessageBox.Show(item["字段名"].ToString() + "应为日期!");
                            return;
                        }
                    }
                    insertValStr += "'" + temp[0].Text + "',";
                }

            }
            insertValStr = "INSERT INTO " + tableName + " VALUES(" + insertValStr[0..^1] + @");
            UPDATE ZY_T_D_TablesInfo
            SET cur_id0 = " + primaryKeyText.Text + @"
            WHERE table_name = '" + tableName + "'";

            if (ExcuteSQL(insertValStr) == 1)
            {
                this.Close();
            }
        }

        /// <summary>
        /// 判断字段类型(0,数值;1,字符;2,日期)
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        private static int GetColumnType(string typeName)
        {
            if (typeName.ToLower().Contains("int") || typeName.ToLower().Contains("decimal") 
                || typeName.ToLower().Contains("bit") || typeName.ToLower().Contains("float"))
            {
                return 0;
            }
            else if (typeName.ToLower().Contains("date"))
            {
                return 2;
            }
            else
            {
                return 1;
            }
        }

        /// <summary>
        /// sql执行
        /// </summary>
        /// <param name="sqlStr"></param>
        /// <returns></returns>
        private int ExcuteSQL(string sqlStr)
        {
            try
            {
                var excuteReponse = string.Empty;
                try
                {
                    db.ExecuteNonQuery(string.Format(sqlStr, tableName));
                }
                catch (Exception ex)
                {
                    excuteReponse = ex.Message;
                }
                if (!string.IsNullOrWhiteSpace(excuteReponse))
                {
                    MessageBox.Show(excuteReponse);
                    return 0;
                }
                else
                {
                    MessageBox.Show("添加成功");
                    return 1;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return 0;
            }
        }
    }
}
